package com.ztesoft.web.resourcecheck;

import org.springframework.stereotype.Component;

import com.ztesoft.core.protocol.client.TelnetClientUtils;
import com.ztesoft.core.protocol.common.CommandResultDto;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.exception.ExceptionHandler;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.Util;
import com.ztesoft.web.common.vo.HostInfoPOJO;


/**
 * TELNET登录方式，执行系统命令<br>
 * 
 * @author <a href="mailto:lin.weibin@zte.com.cn">lin.wb</a> 2016年5月5日 下午7:25:32
 * @version 1.0
 */
@Component
public class TelNetCheckStrategy extends CheckStrategy{

	private static final ZTEsoftLogManager LOGGER = ZTEsoftLogManager
			.getLogger(TelNetCheckStrategy.class);

	private int timeoutInt = 3000;
	
	@Override
	public String check(HostInfoPOJO hostInfoPOJO, int checkType) throws BaseAppException {
    	return Util.dealResult(this.telnetExec(hostInfoPOJO, Util.getExecCmd(hostInfoPOJO.getOsType(), checkType)));
	}
	@Override
	public String checkT(HostInfoPOJO hostInfoPOJO, String shellCommand) throws BaseAppException {
    	return Util.dealResultT(this.telnetExec(hostInfoPOJO, shellCommand));
	}
	@Override
	public String checkIfxLMode(HostInfoPOJO hostInfoPOJO, String dbName, String tableName) throws BaseAppException {
    	String execCmd = DMSConstant.IFX_LMODE_CMD;
		execCmd = execCmd.replaceAll("\\{0\\}",dbName);//
		execCmd = execCmd.replaceAll("\\{1\\}",tableName);//
		return this.telnetExec(hostInfoPOJO, execCmd);

	}

	private String telnetExec(HostInfoPOJO hostInfoPOJO, String execCmd) throws BaseAppException {
		// 
    	TelnetClientUtils tu = null;
		try {
			long tt = System.currentTimeMillis();
			tu = new TelnetClientUtils(hostInfoPOJO.getHostIp(), hostInfoPOJO.getUserName(), hostInfoPOJO.getPwd(), hostInfoPOJO.getPort());
			tu.login(hostInfoPOJO.getUserName(), hostInfoPOJO.getPwd());
			CommandResultDto dto = tu.exec(execCmd, timeoutInt);
			LOGGER.info("耗时{0},查询{1},结果:{2}",(System.currentTimeMillis()-tt)+"ms", execCmd, dto.getCommandResult());
			//对结果做处理 很重要！！！
			return dto.getCommandResult();
		} catch (Exception e) {
			// 
			LOGGER.error("ssh方式执行监测异常{0}",execCmd);
			throw ExceptionHandler.publish("telnet方式执行监测异常", e);
		} finally {
			if (tu!=null) {				
				tu.returnTelnetClient();
			}
		}
		
	}

}
